<template>
  <div class="admin--page-content">
    <div class="admin--form">
      <table class="admin--form--table">
        <colgroup>
          <col style="width: 140px;">
          <col>
        </colgroup>
        <tbody>
          <tr>
            <th><div>아이템명</div></th>
            <td class="admin--table-title">{{ data.name || "-" }}</td>
          </tr>
          <tr>
            <th><div>구분</div></th>
            <td>
              <span :class="['admin--badge', typeBadgeClass(data.type)]">{{ typeLabel(data.type) }}</span>
            </td>
          </tr>
          <tr v-if="data.type !== 'T'">
            <th><div>포인트</div></th>
            <td>{{ data.point !== null && data.point !== undefined ? data.point + "P" : "-" }}</td>
          </tr>
          <tr>
            <th><div>이미지</div></th>
            <td>
              <div v-if="data.file_path" class="onboard--photo-item">
                <img :src="getImageUrl(data.file_path)" :alt="data.file_name || data.name" />
              </div>
              <template v-else>-</template>
            </td>
          </tr>
          <tr>
            <th><div>상태</div></th>
            <td>
              <span :class="['admin--badge', data.status_YN === 'Y' ? 'admin--badge-active' : 'admin--badge-ended']">
                {{ data.status_YN === "Y" ? "사용중" : "미사용" }}
              </span>
            </td>
          </tr>
          <tr>
            <th><div>등록일</div></th>
            <td>{{ formatDateTime(data.created_at) }}</td>
          </tr>
          <tr>
            <th><div>최근 수정</div></th>
            <td>{{ formatDateTime(data.updated_at) }}</td>
          </tr>
        </tbody>
      </table>

      <!-- 버튼 영역 -->
      <div class="admin--form-actions">
        <button type="button" class="admin--btn" @click="goToList">
          ← 목록으로
        </button>
        <button type="button" class="admin--btn admin--btn-red-border ml--auto" @click="handleDelete">
          삭제
        </button>
        <button type="button" class="admin--btn admin--btn-red" @click="goToEdit">
          수정
        </button>
      </div>

      <!-- 알림 모달 -->
      <AdminAlertModal
        v-if="alertModal.show"
        :title="alertModal.title"
        :message="alertModal.message"
        :type="alertModal.type"
        @confirm="handleAlertConfirm"
        @cancel="handleAlertCancel"
        @close="closeAlertModal"
      />
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted } from "vue";
  import { useRoute, useRouter } from "vue-router";
  import AdminAlertModal from "~/components/admin/AdminAlertModal.vue";

  definePageMeta({
    layout: "admin",
    middleware: ["auth"],
  });

  const route = useRoute();
  const router = useRouter();
  const { get, del } = useApi();
  const { getImageUrl } = useImage();

  const itemId = route.params.id;

  const data = ref({
    name: "",
    type: "",
    point: null,
    file_name: "",
    file_path: "",
    status_YN: "Y",
    created_at: "",
    updated_at: "",
  });

  // 구분 라벨/뱃지
  const typeLabel = (t) => (t === "T" ? "진출권" : t === "P" ? "포인트" : t === "B" ? "뱃지" : "-");
  const typeBadgeClass = (t) =>
    t === "T" ? "item--ticket" : t === "P" ? "item--point" : t === "B" ? "item--badge" : "";

  // 알림 모달
  const alertModal = ref({ show: false, title: "알림", message: "", type: "alert", onConfirm: null });
  const showAlert = (message, title = "알림") => {
    alertModal.value = { show: true, title, message, type: "alert", onConfirm: null };
  };
  const showConfirm = (message, onConfirm, title = "확인") => {
    alertModal.value = { show: true, title, message, type: "confirm", onConfirm };
  };
  const closeAlertModal = () => { alertModal.value.show = false; };
  const handleAlertConfirm = () => {
    if (alertModal.value.onConfirm) alertModal.value.onConfirm();
    closeAlertModal();
  };
  const handleAlertCancel = () => closeAlertModal();

  // 상세 조회
  const loadDetail = async () => {
    const { data: res, error } = await get(`/item/${itemId}`);
    if (error || !res?.success) {
      showAlert(error?.message || res?.message || "조회에 실패했습니다.", "오류");
      return;
    }
    const row = res.data || {};
    data.value = {
      name: row.name ?? "",
      type: row.type ?? "",
      point: row.point ?? null,
      file_name: row.file_name ?? "",
      file_path: row.file_path ?? "",
      status_YN: row.status_YN ?? "Y",
      created_at: row.created_at ?? "",
      updated_at: row.updated_at ?? "",
    };
  };

  // 삭제
  const handleDelete = () => {
    showConfirm(
      `'${data.value.name}' 아이템을 삭제하시겠습니까?`,
      async () => {
        const { data: res, error } = await del(`/item/${itemId}`);
        if (error || !res?.success) {
          showAlert(error?.message || res?.message || "삭제에 실패했습니다.", "오류");
        } else {
          showAlert(res.message || "삭제되었습니다.", "성공");
          setTimeout(() => router.push("/site-manager/item/list"), 800);
        }
      },
      "아이템 삭제"
    );
  };

  // 이동
  const goToList = () => router.push("/site-manager/item/list");
  const goToEdit = () => router.push(`/site-manager/item/edit/${itemId}`);

  // 일시 포맷
  const formatDateTime = (dateString) => {
    if (!dateString) return "-";
    const date = new Date(dateString.replace(" ", "T"));
    if (isNaN(date.getTime())) return dateString;
    return date.toLocaleString("ko-KR", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  onMounted(() => {
    loadDetail();
  });
</script>
